const db = require('../db/index')
const bcrypt = require('bcryptjs')

//获取用户信息处理
exports.userinfo = (req, res) => {
    let p1 = new Promise((resolve,reject)=>{
        db.query('select * from users where id=?', req.user.id, (err, result) => {
            if (err) return reject(err)
            if (result.length !== 1) return reject('获取用户信息失败')
            delete result[0].password //返回时不显示 密码字段
            resolve(result[0])
        })
    })

    let p2 = new Promise((resolve,reject)=>{
        db.query('select count(*) as count from reimbursement where user_id =?',req.user.id,(err,result)=>{
            if(err) return reject(err)
            resolve(result[0].count)
        })
    })

    Promise.all([p1,p2]).then(result=>{
        res.send({
            code:200,
            message:"查询成功",
            data:Object.assign(result[0],{count:result[1]})
        })
    }).catch(error=>{
        res.send({
            code:500,
            message:'获取用户信息失败',
            data:error
        })
    })
}

//修改用户信息
exports.updateUserinfo = (req, res) => {
    db.query('update users set? where id=?', [req.body, req.user.id], (err, result) => {
        if (err) return res.send({
            code: 500,
            message:'操作失败',
            data: err

        })
        if (result.affectedRows !== 1) return res.send({
            code: 500,
            message: '修改用户信息失败',
            data: {}
        })
        res.send({
            code: 200,
            message: '修改用户信息成功',
            data: {}

        })
    })
}

//更新用户密码
exports.updatepwd =(req,res)=>{
    db.query('select * from users where id=?',req.user.id,(err,result)=>{
        if(err) return res.send({
            code:500,
            message:"操作失败",
            data:err
        })
        if(result.length!==1) return res.send({
            code:500,
            message:"用户不存在",
            data:{}
        })
        //判断用户输入的旧密码是否正确
        const isPswwod = bcrypt.compareSync(req.body.oldPwd,result[0].password)
        if(!isPswwod) return res.send({
            code:500,
            message:'密码错误',
            data:{}
        })
        //新密码的加密
        const newPwd = bcrypt.hashSync(req.body.newPwd,10)

        db.query('update users set password=? where id=?',[newPwd,req.user.id],(err,result)=>{
            if(err) return res.send({
                code:500,
                message:'操作失败',
                data:err
            })

            if(result.affectedRows !==1) return res.send({
                code:500,
                message:'更新密码失败',
                data:{}
            })

            res.send({
              code:200,
              message:'更新密码成功',
              data:{}
            })
        })
    })
}
